<?php

namespace App\Http\Controllers;

use App\Models\Admins;
use Illuminate\Http\Request;
use Illuminate\Foundation\Auth\AuthenticatesUsers;
use GuzzleHttp\Client;

class AuthController extends Controller
{
    use AuthenticatesUsers;

    /**
     * 用户登陆
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     * @throws \GuzzleHttp\Exception\GuzzleException
     */
    public function login(Request $request){
        try {
            $account = $request->get('openid');
            $password = bcrypt($account);
            //判断用户是否存在
            $user = Admins::where('openid',$account)->first();
            if(!$user){
                //不存在创建新用户
                Admins::create([
                    'openid' => $account,
                    'password' => $password,
                    'role_id'   => 1,//这里写死1为游客角色
                    'status'   => Admins::STATUS_2,
                ]);
                return $this->returnJson(1,'请联系管理员分配权限');
            }
            if($user['role_id'] == 1 || $user['status'] == Admins::STATUS_2){
                return $this->returnJson(1,'请联系管理员分配权限');
            }
            $client = new Client();
            $url = request()->root() . '/oauth/token';
            $params = array_merge(config('passport.proxy'), [
                'username' => $account,
                'password' => $account,
            ]);
            $response = $client->request('POST', $url, ['form_params' => $params]);
            $token_info = json_decode($response->getBody()->getContents());
            return $this->returnJson(0,'',$token_info);
        } catch (\Exception $e) {
            return $this->returnJson(1, '获取登录权限失败，请联系管理员');
        }

    }

    /**
     * 退出登录
     * @return \Illuminate\Http\JsonResponse|string
     */
    public function logout()
    {
        if (auth()->guard('api')->check()) {
            auth()->guard('api')->user()->token()->delete();
            return $this->returnJson(0,'登出成功,页面即将跳转...');
        }
        return '';
    }





}